package com.lu.sb211201rocketmq.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//@PropertySource(value = "classpath:application.yml")
//@ConfigurationProperties(prefix = "rocketmq.producer")
@Configuration
@Slf4j
public class MQProducerConfiguration {

    @Value("${rocketmq.producer.groupName}")
    private String groupName;

    @Value("${rocketmq.producer.namesrvAddr}")
    private String namesrvAddr;

    @Value("${rocketmq.producer.maxMessageSize}")
    private Integer maxMessageSize;

    @Value("${rocketmq.producer.sendMsgTimeout}")
    private Integer sendMsgTimeout;

    @Value("${rocketmq.producer.retryTimesWhenSendFailed}")
    private Integer retryTimesWhenSendFailed;

    @Value("${rocketmq.producer.instanceName}")
    private String instanceName;

//    @Value("${logging.config}")
//    private String log4j2Config;

    @Bean
    public DefaultMQProducer getRocketMQProducer() {
//        System.setProperty("rocketmq.client.log4j2.resource.fileName", log4j2Config);

        DefaultMQProducer producer = new DefaultMQProducer(this.groupName);
        producer.setNamesrvAddr(this.namesrvAddr);
        //如果需要同一个jvm中不同的producer往不同的mq集群发送消息，需要设置不同的instanceName
        producer.setInstanceName(instanceName);
        if (this.maxMessageSize != null) {
            producer.setMaxMessageSize(this.maxMessageSize);
        }
        if (this.sendMsgTimeout != null) {
            producer.setSendMsgTimeout(this.sendMsgTimeout);
        }
        //如果发送消息失败，设置重试次数，默认为2次
        if (this.retryTimesWhenSendFailed != null) {
            producer.setRetryTimesWhenSendFailed(this.retryTimesWhenSendFailed);
        }
        try {
            producer.start();
            log.info("producer is start ! groupName:{},namesrvAddr:{}", this.groupName, this.namesrvAddr);
        } catch (MQClientException e) {
            log.error("producer is error {}", e.getMessage());
        }
        return producer;
    }
}
